<!-- App.vue -->
<template>
  <div id="app">
    <div class="container">
      <header>
        <h1>MBTI性格测试</h1>
        <div class="settings" v-if="!showResult">
          <label>每页题目数量:</label>
          <select v-model="perPage" @change="updatePerPage">
            <option value="5">5题</option>
            <option value="50">50题</option>
          </select>
        </div>
        <div class="progress-bar">
          <div class="progress" :style="{width: progress + '%'}"></div>
        </div>
        <p>已完成 {{ answered }}/{{ totalQuestions }} 题</p>
      </header>

      <QuestionPage
        v-if="!showResult"
        :questions="currentPageQuestions"
        :current-page="currentPage"
        :total-pages="totalPages"
        @answer-selected="handleAnswer"
        @navigate="handleNavigation"
        @complete-test="handleTestComplete"
      />

      <ResultPage
        v-else
        :mbti-result="mbtiResult"
        @restart-test="handleRestart"
      />
    </div>
  </div>
</template>

<script>
import QuestionPage from './components/QuestionPage.vue'
import ResultPage from './components/ResultPage.vue'
import { apiService } from './utils/api'

export default {
  name: 'App',
  components: {
    QuestionPage,
    ResultPage
  },
  data() {
    return {
      sessionKey: null,
      currentPage: 1,
      totalPages: 0,
      totalQuestions: 0,
      currentPageQuestions: [],
      answered: 0,
      progress: 0,
      showResult: false,
      mbtiResult: null,
      perPage: 5 // 默认每页5题
    }
  },
  async created() {
    this.sessionKey = this.getSessionKey()
    // 从本地存储读取每页题目数量设置
    const savedPerPage = localStorage.getItem('mbti_per_page')
    if (savedPerPage) {
      this.perPage = parseInt(savedPerPage)
    }
    await this.loadQuestions(this.currentPage)
    await this.loadProgress()
  },
  methods: {
    getSessionKey() {
      let sessionKey = localStorage.getItem('mbti_session_key')
      if (!sessionKey) {
        sessionKey = 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
        localStorage.setItem('mbti_session_key', sessionKey)
      }
      return sessionKey
    },

    async loadQuestions(page) {
      try {
        const data = await apiService.getQuestions(page, this.sessionKey, this.perPage)

        // 确保每个题目对象都有必要的属性
        this.currentPageQuestions = data.questions.map(q => ({
          ...q,
          answerValue: q.answerValue || null,
          answered: q.answered || false
        }))

        this.currentPage = data.current_page
        this.totalPages = data.total_pages
        this.totalQuestions = data.total_questions
      } catch (error) {
        console.error('加载题目失败:', error)
        alert('加载题目失败，请刷新页面重试')
      }
    },

    async loadProgress() {
      try {
        const data = await apiService.getProgress(this.sessionKey)
        this.answered = data.answered
        this.progress = data.progress
      } catch (error) {
        console.error('加载进度失败:', error)
      }
    },

    updatePerPage() {
      // 保存设置到本地存储
      localStorage.setItem('mbti_per_page', this.perPage.toString())
      // 重新加载当前页
      this.loadQuestions(this.currentPage)
    },

    handleAnswer(questionId, answerValue) {
      // 更新本地状态
      const questionIndex = this.currentPageQuestions.findIndex(q => q.id === questionId)
      if (questionIndex !== -1) {
        this.currentPageQuestions[questionIndex].answerValue = answerValue
        this.currentPageQuestions[questionIndex].answered = true
      }

      // 提交答案到后端
      this.submitAnswers()
    },

    async submitAnswers() {
      // 收集当前页所有已回答的题目
      const answers = {}
      this.currentPageQuestions.forEach(q => {
        if (q.answered && q.answerValue !== null) {
          answers[q.id] = q.answerValue
        }
      })

      try {
        await apiService.submitAnswers(this.sessionKey, answers)
        await this.loadProgress()
      } catch (error) {
        console.error('提交答案失败:', error)
      }
    },

    async handleNavigation(direction) {
      if (direction === 'next' && this.currentPage < this.totalPages) {
        this.currentPage++
        await this.loadQuestions(this.currentPage)
      } else if (direction === 'prev' && this.currentPage > 1) {
        this.currentPage--
        await this.loadQuestions(this.currentPage)
      }
    },

    async handleTestComplete() {
      try {
        const result = await apiService.getResult(this.sessionKey)
        this.mbtiResult = result.mbti_result
        this.showResult = true
      } catch (error) {
        console.error('获取结果失败:', error)
        alert('计算结果失败，请重试')
      }
    },

    handleRestart() {
      // 清除本地存储和状态，重新开始
      localStorage.removeItem('mbti_session_key')
      this.sessionKey = this.getSessionKey()
      this.currentPage = 1
      this.answered = 0
      this.progress = 0
      this.showResult = false
      this.mbtiResult = null
      this.loadQuestions(this.currentPage)
      this.loadProgress()
    }
  }
}
</script>

<style>
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: 'Arial', sans-serif;
  line-height: 1.6;
  color: #333;
  background-color: #f5f5f5;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

header {
  text-align: center;
  margin-bottom: 30px;
}

h1 {
  color: #2c3e50;
  margin-bottom: 15px;
}

.settings {
  margin-bottom: 15px;
}

.settings label {
  margin-right: 10px;
}

.settings select {
  padding: 5px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.progress-bar {
  height: 10px;
  background-color: #ecf0f1;
  border-radius: 5px;
  margin-bottom: 10px;
  overflow: hidden;
}

.progress {
  height: 100%;
  background-color: #3498db;
  transition: width 0.3s ease;
}
</style>
